package com.xinnet.mms.dept.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xinnet.mms.area.dao.AreaDao;
import com.xinnet.mms.company.dao.CompanyDao;
import com.xinnet.mms.dept.dao.DeptDao;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.deptarea.dao.DeptAreaDao;
import com.xinnet.mms.deptproduct.dao.DeptProductDao;
import com.xinnet.mms.entity.Area;
import com.xinnet.mms.entity.Company;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.Dept;
import com.xinnet.mms.entity.DeptArea;
import com.xinnet.mms.entity.DeptProduct;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.login.dao.EmpDao;
import com.xinnet.mms.product.dao.ProductDao;

@Service("deptService")
public class DeptServiceImpl implements DeptService {

	@Autowired
	private DeptDao deptDao;
	@Autowired
	private DeptAreaDao deptAreaDao;
	@Autowired
	private DeptProductDao deptProductDao;
	@Autowired
	private EmpDao empDao;
	@Autowired
	private AreaDao areaDao;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private CompanyDao companyDao;
	
	
	

	public List<Dept> getDeptList() {
		List<Dept> deptList = deptDao.getDeptList();
		return deptList;
	}

	public Dept getDeptByDeptId(String deptId) {
		Dept dept = deptDao.getDeptByDeptId(deptId);
		if (dept == null) {
			return null;
		}
		List<Area> usedAreaList = deptAreaDao.getAreaListByDeptId(deptId);
		String areaParentId = "";
		if(usedAreaList!=null && usedAreaList.size()>0){
			areaParentId = usedAreaList.get(0).getParentId();
		}

		List<Area> parentAreaList = areaDao.getAreaOfClassA();
		
		List<Area> allAreaList = null;
		if(!"".equals(areaParentId)){
			allAreaList = areaDao.getAreaOfClassByParentId(areaParentId);
		}
		List<Product> usedProductList = deptProductDao.getProductListByDeptId(deptId);
		List<Product> allProductList = productDao.queryEnableProduct();

		List<Area> unUsedAreaList = new ArrayList<Area>();
		if (allAreaList != null && allAreaList.size() > 0) {
			for (Iterator<Area> iterator = allAreaList.iterator(); iterator.hasNext();) {
				Area area = (Area) iterator.next();
				String areaID = area.getAreaID();
				boolean isUse = false;
				if (usedAreaList != null && usedAreaList.size() > 0) {
					for (Iterator<Area> iterator2 = usedAreaList.iterator(); iterator2.hasNext();) {
						Area tempArea = (Area) iterator2.next();
						String tempAreaID = tempArea.getAreaID();
						if (areaID.equals(tempAreaID)) {
							isUse = true;
							break;
						}
					}
				}
				if (!isUse) {
					unUsedAreaList.add(area);
				}
			}
		}
		List<Product> unUsedProductList = new ArrayList<Product>();
		if (allProductList != null && allProductList.size() > 0) {
			for (Iterator<Product> iterator = allProductList.iterator(); iterator.hasNext();) {
				Product product = (Product) iterator.next();
				String id = product.getId();
				boolean isUse = false;
				if (usedProductList != null && usedProductList.size() > 0) {
					for (Iterator<Product> iterator2 = usedProductList.iterator(); iterator2.hasNext();) {
						Product tempProduct = (Product) iterator2.next();
						String tempId = tempProduct.getId();
						if (id.equals(tempId)) {
							isUse = true;
							break;
						}
					}
				}
				if (!isUse) {
					unUsedProductList.add(product);
				}
			}
		}
		
		String companyIdStr = dept.getCompanyIdStr();
		if(null!=companyIdStr && !"".equals(companyIdStr)){
			List<Company> allCompanyList = companyDao.getAllCompanyList();
			List<Company> usedCompanyList = new ArrayList<Company>();
			List<Company> unUsedCompanyList = new ArrayList<Company>();
			if (allCompanyList != null && allCompanyList.size() > 0) {
				String[]  companyIdArray = companyIdStr.split(",");
				for (Iterator<Company> iterator = allCompanyList.iterator(); iterator.hasNext();){
					Company company = (Company) iterator.next();
					String id = company.getId();
					boolean isUse = false;
					for (int i = 0; i < companyIdArray.length; i++) {
						String companyId = companyIdArray[i];
						if (id.equals(companyId)) {
							isUse = true;
							break;
						}
					}
					if(isUse){
						usedCompanyList.add(company);
						
					}else{
						unUsedCompanyList.add(company);
					}
				}
			}
			dept.setUnUsedCompanyList(unUsedCompanyList);
			dept.setUsedCompanyList(usedCompanyList);
			
		}else{
			List<Company> unUsedCompanyList = companyDao.getAllCompanyList();
			dept.setUnUsedCompanyList(unUsedCompanyList);
		}
		dept.setUnUsedAreaList(unUsedAreaList);
		dept.setUnUsedProductList(unUsedProductList);
		dept.setUsedAreaList(usedAreaList);
		dept.setUsedProductList(usedProductList);
		dept.setParentAreaList(parentAreaList);
		dept.setAreaParentId(areaParentId);
		return dept;
	}

	public void addDept(Dept dept) {
		deptDao.addDept(dept);
	}

	public void updateDept(Dept dept, String areaStr, String productStr) {
		String deptId = dept.getId();
		deptDao.updateDept(dept);
		// 更新部门区域
		deptAreaDao.delDeptAreaByDeptId(deptId);
		String[] areaIdArray = areaStr.split(",");
		for (int i = 0; i < areaIdArray.length; i++) {
			DeptArea deptArea = new DeptArea();
			String areaId = areaIdArray[i];
			deptArea.setId(deptId);
			deptArea.setAreaId(areaId);
			deptAreaDao.addDeptArea(deptArea);
		}
		// 更新部门产品
		deptProductDao.delDeptProductByDeptId(deptId);
		String[] productIdArray = productStr.split(",");
		for (int i = 0; i < productIdArray.length; i++) {
			DeptProduct deptProduct = new DeptProduct();
			String productId = productIdArray[i];
			deptProduct.setId(deptId);
			deptProduct.setProductId(productId);
			deptProductDao.addDeptProduct(deptProduct);
		}
	}

	public String delDeptById(String deptId) {
		Emp emp = empDao.getEmpListByDeptId(deptId);
		if (emp != null) {
			return "0";// 部门中有员工不能删除
		}
		deptAreaDao.delDeptAreaByDeptId(deptId);
		deptProductDao.delDeptProductByDeptId(deptId);
		deptDao.delDeptById(deptId);
		return "1";
	}

	public String getDeptTree() {
		StringBuffer nodeStr = new StringBuffer();
		List<Dept> deptList = deptDao.getDeptList();
		if (null == deptList) {
			return null;
		}
		int i = 0;
		for (Iterator<Dept> iterator = deptList.iterator(); iterator.hasNext();) {
			Dept dept = (Dept) iterator.next();
			String id = dept.getId();
			String parentId = dept.getParentId();
			String name = dept.getDname();
			if (i == 0) {
				nodeStr.append("[{id:\"" + id + "\",pId:\"" + parentId
						+ "\",name:\"" + name + "\",open:true}");
			} else {
				nodeStr.append(",{id:\"" + id + "\",pId:\"" + parentId
						+ "\",name:\"" + name + "\"}");
			}
			i++;
		}
		return nodeStr.toString() + "]";
	}

	public String isCanUseTheDeptName(String isUpdate, String dname, String id) {
		if ("true".equals(isUpdate)) {
			Dept dept = deptDao.getDeptByName(dname);
			if (dept == null) {
				return "fase";
			}
			String deptId = dept.getId();
			if (id.equals(deptId)) {
				return "true";
			} else {
				return "false";
			}
		} else {
			Dept dept = deptDao.isCanUseTheDeptName(dname);
			if (dept == null) {
				return "true";
			}
		}
		return "false";
	}

	public void addDepartment(Dept dept, String areaStr, String productStr) {
		String deptId = UUID.randomUUID().toString();
		dept.setId(deptId);
		deptDao.addDept(dept);
		String[] areaIdList = areaStr.split(",");
		for (int i = 0; i < areaIdList.length; i++) {
			DeptArea deptArea = new DeptArea();
			String areaId = areaIdList[i];
			deptArea.setAreaId(areaId);
			deptArea.setId(deptId);
			deptAreaDao.addDeptArea(deptArea);
		}
		String[] productIdList = productStr.split(",");
		for (int i = 0; i < productIdList.length; i++) {
			String productId = productIdList[i];
			DeptProduct deptProduct = new DeptProduct();
			deptProduct.setProductId(productId);
			deptProduct.setId(deptId);
			deptProductDao.addDeptProduct(deptProduct);
		}
	}

	public String updateDeptByDeptId(String deptId) {
		Emp emp = empDao.getEmpListByDeptId(deptId);
		if (emp != null) {
			return "0";// 部门中有员工不能修改
		}
		return "1";
	}

	public Emp getEmpListByDeptId(String deptId) {
		Emp emp = empDao.getEmpListByDeptId(deptId);
		return emp;
	}

	public List<Dept> getDeptByParentId(String deptId) {
		List<Dept> deptList = empDao.getDeptByParentId(deptId);
		return deptList;

	}

	@Override
	public String getDeptTreeByDeptId(String deptId) {
		String deptJson = "";
		Dept dept = null;
		
		//若是没有ID为此ID的部门 则直接返回null
		dept = deptDao.getDeptByDeptId(deptId);
		if(null == dept) {
			return "";
		}
		
		String id = dept.getId();
		String parentId = dept.getParentId();
		String name = dept.getDname();
		
		deptJson += "{id:\"" + id + "\",pId:\"" + parentId + "\",name:\""
				+ name + "\",open:true}";
		
		
		List<Dept> tempList = empDao.getDeptByParentId(deptId);
		
		//如果该部门没有子部门 则返回该部门
		if (null == tempList || tempList.size() == 0) {
			return deptJson;
		} 
		
		//如果该部门有子部门 则返回该部门及其子部门
		for(Dept d : tempList) {
			deptJson += "," + getDeptTreeByDeptId(d.getId());
		}

		return deptJson;
	}
	/**
	 * 获取员工所在的部门信息
	 * @param empNo
	 * @return
	 */
	public Dept getDeptByEmpNo(String empNo){
		Dept dept = deptDao.getDeptByEmpNo(empNo);
		return dept;
	}

	/**
	 * 通过区域ID/产品CODE取得部门
	 */
	@Override
	public Dept getDeptByProductCodeAndAreaId(Customer customer) throws SQLException {
		return deptDao.getDeptByProductCodeAndAreaId(customer);
	}
	
	/**
	 * 获取所有子节点ID
	 * @param deptId
	 * @return
	 */
	public String getChildNodeId(String deptId){
		List<Dept>  deptList = deptDao.getDeptList();
		String deptIdStr = getDeptIdStr(deptList,deptId);
		return deptIdStr+deptId;
			
	}
	private String getDeptIdStr(List<Dept>  deptList,String deptId){
		StringBuffer sb =new StringBuffer();
		if(deptList==null || deptList.size()==0){
			return "";
		}
		
		for (Iterator<Dept> iterator = deptList.iterator(); iterator.hasNext();) {
			Dept dept = (Dept) iterator.next();
			String tempDeptId = dept.getId();
			String parentId= dept.getParentId();
			if(parentId.equals(deptId)){
				sb.append(tempDeptId+",");
				String deptIdStr = this.getDeptIdStr(deptList, tempDeptId);
				sb.append(deptIdStr);
			}
			
		}
		return sb.toString();	
	}	
	
	/**
	 * 获取Dept列表
	 * @param deptIdStr
	 * @return
	 */
	public List<Dept> getDeptListByDeptIdStr(String deptIdStr){
		List<Dept>  deptList = deptDao.getDeptListByDeptIdStr(deptIdStr);
		return deptList;
	}

	/**
	 * 根据产品code 重置部门内所有员工的可分配标签
	 */
	@Override
	public void resetAllotLabelByProductCode(String productCode) throws Exception {
		deptDao.resetAllotLabelByProductCode(productCode);
	}

	/**
	 * 同步部门关系
	 */
	@Override
	public void sysnDeptRelation() throws Exception {
		List<Dept> list=deptDao.getDeptList();
		for(Dept dept:list) {
			String childIds=getChildNodeId(dept.getId());
			String childId[]=childIds.split(",");
			for(int i=0;i<childId.length;i++) {
				Dept tempDept=new Dept();
				tempDept.setRelationId(UUID.randomUUID().toString());
				tempDept.setId(dept.getId());
				tempDept.setChildId(childId[i]);
				if(deptDao.getDeptRelationByDeptnoAndChildId(tempDept)==0) {
					deptDao.addDeptChildRelation(tempDept);
				}
			}
		}
		
	}
	
	/**
	 * 
	 *
	 * 功能描述：获取公司名字
	 * 
	 * @author yanlvshui
	 *
	 * @throws 2014年8月11日
	 *
	 */
	public String getCompanyNameByCompId(String companyId) throws SQLException{
		
		String companyName = this.deptDao.getCompanyNameByCompId(companyId);
		return companyName;
	}

	@Override
	public List<Dept> getDeptByString() {
		// TODO Auto-generated method stub
		return deptDao.getDeptByString();
	}
}
